package com.stu.wgt.test.controller;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.stu.wgt.test.bean.Member;
import com.stu.wgt.test.result.R;
import com.stu.wgt.test.result.ResultCodeEnum;
import com.stu.wgt.test.service.MemberService;
import com.stu.wgt.test.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author wgt
 * @since 2024-01-20
 */
@RestController
@RequestMapping("/member")
public class MemberController {

    @Autowired
    MemberService memberService;

    // 增加会员
    @RequestMapping(value = "/addMember", method = RequestMethod.POST)
    public R addMember(@RequestBody Member member) {
        System.out.println(member);
        member.setPassword(DigestUtils.md5DigestAsHex(member.getPassword().getBytes()));
        int result = memberService.insert(member);
        if (result == 1)
            return R.ok();
        return R.error().data("msg", "添加会员失败");
    }

    // 删除会员
    @DeleteMapping("/{id}")
    public R deleteMember(@PathVariable("id") Integer id) {
        int result = memberService.delete(id);
        if (result == 1)
            return R.ok();
        return R.error().data("msg", "请求参数错误");
    }

    //修改会员
    @PutMapping("/{id}")
    public R updateMember(@PathVariable("id") Integer id, @RequestBody Member member) {
        member.setId(id);
        if(member.getPassword() != null) {
            member.setPassword(DigestUtils.md5DigestAsHex(member.getPassword().getBytes()));
        }
        int result = memberService.update(member);
        if (result == 1) {
            return R.ok().data("msg", "更新成功");
        }
        return R.error().data("msg", "用户更新失败");
    }
    //修改会员
    @PutMapping("/updatePassword/{id}")
    public R updateMemberPassword(@PathVariable("id") Integer id,  @RequestBody Member member) {
        member.setId(id);
        System.out.println(member);
        String password = DigestUtils.md5DigestAsHex(member.getPassword().getBytes());
        List<Member> member1 = memberService.selectById(id);
        if(!member1.get(0).getPassword().equals(password)) {
            return R.setResult(ResultCodeEnum.BAD_REQUEST).data("msg", "密码错误");
        }
        String passwordMd5 = DigestUtils.md5DigestAsHex(member.getConfigurePassword().getBytes());
        member.setPassword(passwordMd5);
        int result = memberService.update(member);
        if (result == 1) {
            return R.ok().data("msg", "更新成功");
        }
        return R.error().data("msg", "用户更新失败");
    }

    //查询会员
    @GetMapping("/selectAllMember")
    public R selectAllMember() {
        try {
            List<Member> memberList = memberService.selectAllMember();
            return R.ok().data("memberlist", memberList).data("total", memberList.size());
        } catch (Exception e) {
            return R.error().data("msg", "查询不到会员");
        }

    }

    //    分页查询
    @GetMapping("/search")
    public R searchUsers(@RequestParam("query") String query,
                         @RequestParam("pagenum") int pageNum,
                         @RequestParam("pagesize") int pageSize) {
        // 根据查询关键字、当前页数和每页显示的数据条数进行查询操作
        try {
            IPage<Member> memberIPage = memberService.searchMember(query, pageNum, pageSize);
            return R.ok().data("member", memberIPage.getRecords()).data("total", memberIPage.getTotal());
        } catch (Exception e) {
            System.out.println(e);
            return R.error().data("msg", "查询失败");
        }
    }

    // 通过ID查找
    @GetMapping("/{id}")
    public R selectMemberById(@PathVariable("id") Integer id) {
        if (id <= 0) {
            return R.error().data("msg", "ID不能为空");
        }
        List<Member> memberList = memberService.selectById(id);
        if (memberList.isEmpty()) {
            return R.error();
        }
        return R.ok().data("memberlist", memberList);
    }

    @RequestMapping("/login")
    public R login(@RequestBody Member member) {
        // 使用 MD5 加密算法对密码进行加密
        String md5Password = DigestUtils.md5DigestAsHex(member.getPassword().getBytes());

        // 检查用户输入的是用户名还是手机号
        List<Member> member1;
        if (member.getName().matches("^1[3-9]\\d{9}$") && member.getName().length() > 10) {
            // 用户输入手机号，通过手机号查询
            member1 = memberService.selectByTelephone(member.getTelephone());
        } else {
            // 用户输入用户名，通过用户名查询
            member1 = memberService.selectByName(member.getName());
        }
        if (member1.isEmpty()) {
            return R.setResult(ResultCodeEnum.NOT_FOUND).data("msg", "用户未注册，请前往注册");
        }
        System.out.println(md5Password + "\n" + member1.get(0).getPassword());
        if (!md5Password.equals(member1.get(0).getPassword())) {
            return R.setResult(ResultCodeEnum.BAD_REQUEST).data("msg", "用户密码输入错误");
        } else {
            String token = JwtUtil.createToken("user");
            return R.ok().data("token", token).data("member", member1);
        }
    }

    @RequestMapping("/register")
    public R register(@RequestBody Member member) {
        System.out.println(member);
        String md5Pass = DigestUtils.md5DigestAsHex(member.getPassword().getBytes());
        member.setPassword(md5Pass);
        // 检查用户名是否已存在
        if (!memberService.selectByName(member.getName()).isEmpty()) {
            return R.setResult(ResultCodeEnum.CONFLICT).data("msg", "用户名已存在");
        }

        // 检查手机号是否已存在
        if (!memberService.selectByTelephone(member.getTelephone()).isEmpty()) {
            return R.setResult(ResultCodeEnum.CONFLICT).data("msg", "手机号已存在");
        }

        // 注册用户
        if (memberService.register(member)) {
            return R.ok().data("msg", "用户注册成功");
        }
        return R.error().data("msg", "用户注册失败");
    }
    /**
     * 用户头像上传
     *
     * @param file
     * @return
     */
    @PostMapping("/upload")
    public R handleFileUpload(@RequestParam("file") MultipartFile file) {
        System.out.println("上传用户头像");
        try {
            String uploadDir = "E:/桌面/毕业设计/代码/后端/src/main/resources/static/image/";
            String originalFileName = file.getOriginalFilename();
            String fileExtension = "";

            // 获取文件后缀（扩展名）
            if (originalFileName != null && originalFileName.lastIndexOf(".") != -1) {
                fileExtension = originalFileName.substring(originalFileName.lastIndexOf("."));
            }
            String uuid = UUID.randomUUID().toString().replace("-", "");//UUID生成不重复的一串数字
            String newFileName = uuid + fileExtension; // 新的文件名 = UUID + 文件扩展名

            File dest = new File(uploadDir + newFileName);
            file.transferTo(dest);

            String tmpPath = newFileName;
            String url = "http://127.0.0.1:8888/image/" + tmpPath;
            return R.ok().data("path", tmpPath).data("url", url);
        } catch (Exception e) {
            e.printStackTrace();
            return R.error();
        }
    }
}

